/*
 * Copyright (C) 2013 Winson Wong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package myidea.winson.android.cangjieime;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.TwoStatePreference;
import android.util.Log;

/**
 * Displays the IME preferences inside the input method setting.
 */
public class ImePreferences extends PreferenceActivity implements OnPreferenceClickListener, OnPreferenceChangeListener{
	
	private static final int MSG_ENABLE_DBUPDATE = 1;
	private static final int MSG_DISABLE_DBUPDATE = 2;
	
	private static final int MSG_PREF_DEFUALT_PICKUP_MODE_CHANGE = 3;
	private static final int MSG_PREF_FORCES_RUN_FULLSCREEN_CHANGE = 4;
	private static final int MSG_PREF_KEYBOARD_KEY_SIZE_MODE_CHANGE = 5;
	
	private static final int MSG_PREF_MIX_INPUT_DISPALY_MODE_CHANGE = 6;
	private static final int MSG_PREF_CANGJIE_INPUT_KEY_CODE_POSITION_CHANGE = 7;
	
	private ListPreference mPrefDefaultPickupMode;
	private ListPreference mPrefForcesRunFullscreen;
	private CheckBoxPreference mPrefSupportCangjieThird;
	private ListPreference mPrefKeyboardKeySizeMode;
	private ListPreference mPrefMixInputDisplayMode;
	private ListPreference mPrefCangjieInputKeyCodePosition;
	private CheckBoxPreference mPrefIsSymbolsPickupChinese;
	private Preferences mPrefs;
	
	Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	switch (msg.what) {
	        	case MSG_ENABLE_DBUPDATE:
	                enableDBUpdate();
	                break;
	        	case MSG_DISABLE_DBUPDATE:
	        		disableDBUpdate();
	        		break;
	        	case MSG_PREF_DEFUALT_PICKUP_MODE_CHANGE:
	        		mPrefDefaultPickupMode.setSummary(mPrefDefaultPickupMode.getEntry());	        		
	        		break;
	        	case MSG_PREF_FORCES_RUN_FULLSCREEN_CHANGE:
	        		mPrefForcesRunFullscreen.setSummary(mPrefForcesRunFullscreen.getEntry());
	        		break;
	        	case MSG_PREF_KEYBOARD_KEY_SIZE_MODE_CHANGE:	        		
	        		mPrefKeyboardKeySizeMode.setSummary(mPrefKeyboardKeySizeMode.getEntry().toString().replace("%", "%%"));
	        		break;
	        	case MSG_PREF_MIX_INPUT_DISPALY_MODE_CHANGE:
	        		mPrefMixInputDisplayMode.setSummary(mPrefMixInputDisplayMode.getEntry());
	        		
	        		switch(Integer.parseInt((String) msg.obj)){
	        			case Preferences.MID_ENGLISH_FIRST:
	        				mPrefIsSymbolsPickupChinese.setEnabled(true);
	        				break;
	        			case Preferences.MID_DEFAULT_FIRST:
	        			case Preferences.MID_DEFAULT_FIRST_WITHOUT_CANDIDATE:
	        				mPrefIsSymbolsPickupChinese.setEnabled(false);
	        				mPrefIsSymbolsPickupChinese.setChecked(true);
	        				break;
	        		}
	        		
	        		break;
	        	case MSG_PREF_CANGJIE_INPUT_KEY_CODE_POSITION_CHANGE:
	        		mPrefCangjieInputKeyCodePosition.setSummary(mPrefCangjieInputKeyCodePosition.getEntry());
	        		break;
        	}
        }
	};
	
    @Override
    public Intent getIntent() {
        final Intent modIntent = new Intent(super.getIntent());
        //modIntent.putExtra(EXTRA_SHOW_FRAGMENT, Settings.class.getName());
        modIntent.putExtra(EXTRA_NO_HEADERS, true);
        return modIntent;
    }
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // We overwrite the title of the activity, as the default one is "Voice Search".
        setTitle(R.string.setting_name);
        addPreferencesFromResource(R.layout.preference);
        
        mPrefs = Preferences.loadPreferences(this);
        
        mPrefDefaultPickupMode = (ListPreference)findPreference(Preferences.PREF_DEFAULT_PICKUP_MODE);
        mPrefDefaultPickupMode.setSummary(mPrefDefaultPickupMode.getEntry());
        mPrefDefaultPickupMode.setOnPreferenceChangeListener(this);
        
        mPrefForcesRunFullscreen = (ListPreference)findPreference(Preferences.PREF_FORCES_RUN_FULLSCREEN);
        mPrefForcesRunFullscreen.setSummary(mPrefForcesRunFullscreen.getEntry());
        mPrefForcesRunFullscreen.setOnPreferenceChangeListener(this);
        
        mPrefSupportCangjieThird = (CheckBoxPreference)findPreference(Preferences.PREF_SUPPORT_CANGJIE_THIRD);
        mPrefSupportCangjieThird.setOnPreferenceChangeListener(this);
        
        mPrefKeyboardKeySizeMode = (ListPreference)findPreference(Preferences.PREF_KEYBOARD_KEY_SIZE_MODE);
        mPrefKeyboardKeySizeMode.setSummary(mPrefKeyboardKeySizeMode.getEntry().toString().replace("%", "%%"));
        mPrefKeyboardKeySizeMode.setOnPreferenceChangeListener(this);
        
        mPrefMixInputDisplayMode = (ListPreference)findPreference(Preferences.PREF_MIX_INPUT_DISPLAY_MODE);
        mPrefMixInputDisplayMode.setSummary(mPrefMixInputDisplayMode.getEntry());
        mPrefMixInputDisplayMode.setOnPreferenceChangeListener(this);
        
        mPrefCangjieInputKeyCodePosition = (ListPreference)findPreference(Preferences.PREF_CANGJIE_INPUT_KEY_CODE_POSITION);
        mPrefCangjieInputKeyCodePosition.setSummary(mPrefCangjieInputKeyCodePosition.getEntry());
        mPrefCangjieInputKeyCodePosition.setOnPreferenceChangeListener(this);
        
        mPrefIsSymbolsPickupChinese = (CheckBoxPreference)findPreference(Preferences.PREF_IS_SYMBOLS_PICKUP_CHINESE);
        
        
        switch(mPrefs.mixInputDisplayMode){
		case Preferences.MID_ENGLISH_FIRST:
			mPrefIsSymbolsPickupChinese.setEnabled(true);
			break;
		case Preferences.MID_DEFAULT_FIRST:
		case Preferences.MID_DEFAULT_FIRST_WITHOUT_CANDIDATE:
			mPrefIsSymbolsPickupChinese.setEnabled(false);
			mPrefIsSymbolsPickupChinese.setChecked(true);
			break;
		
		}
		
        
        PackageInfo pInfo = null;
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        findPreference("version").setSummary(pInfo.versionName);
        
        Preference manual = findPreference("manual");
        manual.setOnPreferenceClickListener(this);
        
    }


	@Override
	public boolean onPreferenceClick(Preference preference) {
		if (preference.getKey().equals("manual")){
			Intent httpIntent = new Intent(Intent.ACTION_VIEW);
			httpIntent.setData(Uri.parse(getResources().getString(R.string.manual_url)));
	
			startActivity(httpIntent);
		}
		
		
		return true;
	}

	private void enableDBUpdate(){
		mPrefSupportCangjieThird.setEnabled(true);
		mPrefSupportCangjieThird.setSummary("");
	}
	
	private void disableDBUpdate(){
		mPrefSupportCangjieThird.setEnabled(false);
		mPrefSupportCangjieThird.setSummary(R.string.pref_updateing_database_summary);
	}
	

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if(preference == mPrefSupportCangjieThird){
			prefSupportCangjieThirdChange(((Boolean) newValue).booleanValue());
		}
		else if(preference == mPrefDefaultPickupMode){
			Message message = new Message();
	        message.what = ImePreferences.MSG_PREF_DEFUALT_PICKUP_MODE_CHANGE;
	        message.obj = newValue;
	        mHandler.sendMessage(message);
		}
		else if(preference == mPrefForcesRunFullscreen){
			Message message = new Message();   
	        message.what = ImePreferences.MSG_PREF_FORCES_RUN_FULLSCREEN_CHANGE;
	        message.obj = newValue;
	        mHandler.sendMessage(message);
		}
		else if(preference == mPrefKeyboardKeySizeMode){
			Message message = new Message();   
	        message.what = ImePreferences.MSG_PREF_KEYBOARD_KEY_SIZE_MODE_CHANGE;
	        message.obj = newValue;
	        mHandler.sendMessage(message);
		}
		else if(preference == mPrefMixInputDisplayMode){
			Message message = new Message();   
	        message.what = ImePreferences.MSG_PREF_MIX_INPUT_DISPALY_MODE_CHANGE;
	        message.obj = newValue;
	        mHandler.sendMessage(message);
		}
		else if(preference == mPrefCangjieInputKeyCodePosition){
			Message message = new Message();   
	        message.what = ImePreferences.MSG_PREF_CANGJIE_INPUT_KEY_CODE_POSITION_CHANGE;
	        message.obj = newValue;
	        mHandler.sendMessage(message);
		}
		return true;
	}
	
	private void prefSupportCangjieThirdChange(boolean newValue){
		
		
		CangjieInput cangjieInput = new CangjieInput(this);
		Message message = new Message();   
        message.what = ImePreferences.MSG_DISABLE_DBUPDATE;
		mHandler.sendMessage(message);
		
		message = new Message();
		message.what = ImePreferences.MSG_ENABLE_DBUPDATE;
		if (newValue){
			cangjieInput.addCangjie3(mHandler, message);			
		}
		else{
			cangjieInput.removeCangjie3(mHandler, message);
		}
	}

    /*
    public static class Settings extends InputMethodSettingsFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setInputMethodSettingsCategoryTitle(R.string.language_selection_title);
            setSubtypeEnablerTitle(R.string.select_language);

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.ime_preferences);
        }
    }
  	*/
}
